import { Subject, combineLatest } from 'rxjs'
import { MeetingEntity } from './interfaces/meeting'
import { map, startWith } from 'rxjs/operators'
import PinyinMatch from 'pinyin-match'
import { fetchGetMeetingList } from '@/api/index'

//TODO: 会议参数
class Service {
	meetingList$ = new Subject<MeetingEntity[]>()
	filteredMeetingList$ = new Subject<MeetingEntity[]>()
	search$ = new Subject<string>()
	hasFirstLoad$ = new Subject<boolean>()
	constructor() {
		combineLatest([this.meetingList$, this.search$.pipe(startWith(''))])
			.pipe(
				map(([allList, keyword]) => {
					return allList.filter((x) => {
						//去除搜索字符前面的字符串
						var toSearchKeyword = keyword.replace(new RegExp('^([\\s]*)(.*)$'), '$2')
						return (
							x.e164.includes(toSearchKeyword) ||
							x.meetingName.includes(toSearchKeyword) ||
							x.organiger.includes(toSearchKeyword) ||
							PinyinMatch.match(x.organiger, toSearchKeyword) ||
							PinyinMatch.match(x.meetingName, toSearchKeyword)
						)
					})
				})
			)
			.subscribe(this.filteredMeetingList$)
		// this.filteredMeetingList$
	}
	setMeetingList(params: MeetingEntity[]) {
		this.meetingList$.next(params)
	}
	refreshList() {
		fetchGetMeetingList().then((res: any) => {
			this.hasFirstLoad$.next(true)
			res && this.setMeetingList(res)
		})
	}
	doLocalFilter(searchText: string) {
		this.search$.next(searchText)
	}
}
export default new Service()
